const mongoose = require('mongoose')
const { Types } = require('mongoose')
const Schema = mongoose.Schema

const moment = require('moment')

const articleSchema = new Schema({
  // _id: Types.ObjectId,
  author_id: {
    type: Types.ObjectId,
    index: true
  },
  title: {
    type: String,
    default: ""
  },
  desc: {
    type: String,
    default: ""
  },
  content: String,
  publish: {
    type: Boolean,
    default: false
  },
  readCount: {  // 阅读量
    type: Number,
    default: 0,
  },
  star: {       // 点赞
    type: Number,
    default: 0,
  },
  favorite: {   // 收藏
    type: Number,
    default: 0
  },
  createDate: {
    type: Date,
    default: Date.now()
  },
  publishDate: {
    type: Date,
    default: null
  },
  lastEditDate: {
    type: Date,
    default: null
  },
  tags: {
    type: [Object],
    default: []
  },
  category: {
    type: Object,
    default: null
  }
})

articleSchema.set('toJSON', { getters: true, virtuals: true })
articleSchema.set('toObject', { getters: true, virtuals: true })
// 国际化-中国
moment.locale('zh-cn')
articleSchema.path('createDate').get(function (v) {
  // utcOffset(8)中国时区
  return moment(v).utcOffset(8).format('lll') // xxxx年xx月xx日 hh:ss
})
articleSchema.path('publishDate').get(function (v) {
  if (!v) { return null }
  // utcOffset(8)中国时区
  return moment(v).utcOffset(8).format('lll') // xxxx年xx月xx日 hh:ss
})
articleSchema.path('lastEditDate').get(function (v) {
  if (!v) { return null }
  // utcOffset(8)中国时区
  return moment(v).utcOffset(8).format('lll') // xxxx年xx月xx日 hh:ss
})

const articleModel = mongoose.model('article', articleSchema)

module.exports = {
  articleModel
}